package com.crwal.app.utils;

import java.io.File;
import java.util.List;

import com.crwal.app.bean.News;

import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExcelUtils {

	/**
	 * 导出excel文件
	 * @param tempLocDirectory 本地文件路径
	 * @param fileName 文件名称
	 * @param list 数据集合
	 */
	public static void exportCrwalResult(String tempLocDirectory, String fileName, List<News> list) {
        try {
        	File file = new File(tempLocDirectory);
        	if(!file.exists()){
        		file.mkdirs();
        	}
        	String filePath = tempLocDirectory+fileName;
    		log.debug("开始导出文件："+filePath);
    		
    		// 通过工具类创建writer
    		ExcelWriter writer = ExcelUtil.getWriter(filePath);
    		
    		//自定义excel标题和列名
    		writer.addHeaderAlias("company","公司名");
    		writer.addHeaderAlias("companyHref","公司网站");
    		writer.addHeaderAlias("title","文章标题");
    		writer.addHeaderAlias("href","文章地址");
    		writer.addHeaderAlias("abstractContent","文章摘要");
    		writer.addHeaderAlias("publishDate","发布时间");
    		writer.addHeaderAlias("keywords","关键字");
    		writer.addHeaderAlias("times","关键字频率");
    		// 一次性写出内容，使用默认样式，强制输出标题
    		writer.write(list, true);
    		// 关闭writer，释放内存
    		writer.close();
            log.debug("导出文件成功！");
        }catch(Exception e) {
        	e.printStackTrace();
            log.error("导出文件失败！",e);
        }finally {
        }
	}
	
	/**
	 * 读取excel文件内容
	 * @param tempLocDirectory 本地文件路径
	 * @param fileName 文件名称
	 * @return
	 */
	public static List<News> readExcel(String tempLocDirectory, String fileName){
        ExcelReader reader = ExcelUtil.getReader(tempLocDirectory+fileName);
        reader.addHeaderAlias("公司名", "company");
		reader.addHeaderAlias("公司网站", "companyHref");
		reader.addHeaderAlias("文章标题", "title");
		reader.addHeaderAlias("文章地址", "href");
		reader.addHeaderAlias("文章摘要", "abstractContent");
		reader.addHeaderAlias("发布时间", "publishDate");
		reader.addHeaderAlias("关键字", "keywords");
		reader.addHeaderAlias("关键字频率", "times");
        List<News> newsList = reader.readAll(News.class);
        //日志输出读取到的信息
        //log.debug(newsList.toString());
        reader.close();
        return newsList;
    }
	
	public static boolean deleteFile(String filePath) {
		return FileUtil.del(filePath);
	}

	
}
